<?php
declare (strict_types = 1);

namespace app\service\model;

use app\common\model\BaseModel;
use app\myself\Bc;
use app\order\model\Order;
use app\order\model\OrderGoods;
use app\order\model\OrderInfo;
use app\Request;
use app\shop\model\ShopOrderLog;
use app\shop\model\ShopUsers;
use app\user\model\User;
use League\Flysystem\Exception;
use think\Model;

/**
 * @mixin \think\Model
 */
class Service extends BaseModel
{
    public function getPriceAttr($value){
        return number_format($value/100,2,'.','');
    }

    //  状态1-申请，2-商家已审核，3-等待买家寄货，4-等待卖家(type=1 ? '收' : '发')货，5-已完成，6-已拒绝

    // 售后列表
    public function applyPlay($base)
    {
        // 获取到 订单id, 类型， 图片，申请退款金额，申请理由
        list($oid,$type,$cover,$price,$apply_reason,$good_id,$order_goods_id,$num) =  $base->getSetDefaultParams("oid,type,cover| ,price|0,apply_reason| ,good_id|-1,order_goods_id|-1,num|1");
        if(!is_numeric($price)) return retu_json(400,'请填写正确的退款金额，小数点后保留2位!');
        if(!$orderGoodsModel = OrderGoods::find($order_goods_id))return retu_json(400,'订单商品记录不存在');
        if(!$orderModel = Order::where('uid',$base->user->id)->find($oid))return retu_json(400,'订单没有该记录');
        // 如果不是同一个订单
        if($orderGoodsModel->order_id != $orderModel->id)return retu_json(400,'订单商品和订单不是同一个');
        // 当前订单 处于  待发货2-已收货4之间
        if($orderModel->status < 2)return retu_json(400,'订单未付款');
        if($orderModel->status == 5)return retu_json(400,'订单已完成');
        // 该订单没有售后过
        if($orderModel->service != 0)return retu_json(400,'当前订单已经申请售后过');
        // 该订单商品没有售后过
        if($orderGoodsModel->service != 0)return retu_json(400,'当前订单商品已经申请售后过');
        // 数量
        if(!$num || $num <= 0)$num = 1;
        if($num > $orderGoodsModel->num)return retu_json(400,'申请数量不得大于购买数量');
        // 避免金额过小
        if($price < 0) $price = 0;
        // 判断订单商品金额 小于 退货金额
        if($orderGoodsModel->total < $price * 100)return retu_json(400,'申请金额不得超过订单实际支付金额');
        // if($orderGoodsModel->total < $price * 100)$price = $orderGoodsModel->total / 100;
        // 当前 订单没有出现在 售后中
        if($this::where('order_id',$orderModel->id)->count())
            return retu_json(400,'售后订单已存在');
        // 生成退货号
        $service_sn = md5($orderModel->order_sn).'-'.time();
        $this::startTrans();
        try{
            // 插入售后服务 -
            $serviceData = [
                'uid' => $base->user->id, //用户id
                'order_id' => $oid, //订单id
                'order_orn' => $orderModel->order_sn, // 订单号
                'service_sn' => $service_sn, // 退货号
                'type' => $type, // 类型
                'cover' => $cover,// 图片数据
                'price' => $price * 100, // 退货金额
                'volume' => $orderModel->volume * 100, // 购物券退还金额
                'apply_reason' => $apply_reason, // 申请理由
                'add_time' => time(),  // 申请售后时间
                'order_goods_id' => $order_goods_id,
                'apply_num' => $num
            ];
            // 如果有店铺
            if($orderModel->shop_id && $orderModel->shop_id > 2)$serviceData['shop_id'] = $orderModel->shop_id;
            $id = $this->insertGetId($serviceData);
            if(!$id)return retu_json(400,'插入记录错误,麻烦重新尝试');
            // 插入售后 商品表数据
            $ServiceGoodsData = [
                'service_id' => $id, // 售后关联id
                'order_goods_id' => $order_goods_id, // 订单商品id
                'num' => $orderGoodsModel->num, // 数量
                'oid' => $oid
            ];
            $id1 = ServiceGoods::insertGetId($ServiceGoodsData);
            if(!$id1)return retu_json(400,'插入记录错误,麻烦重新尝试111');
            Order::where('id',$orderModel->id)->update([
               'service' => 1 // 更改状态
            ]);
            OrderGoods::where('id',$orderGoodsModel->id)->update(['service' => 1]);
            // 店铺订单改变数据
            if($orderModel->shop_id && $orderModel->shop_id > 1){
                ShopOrderLog::where([
                    'shop_id' => $orderModel->shop_id,
                    'oid' => $orderModel->id,
                    'order_goods_id' => $orderGoodsModel->id
                ])->update([
                    'retuen_status' => $type, // 更新退款状态信息
                ]);
            }
            $this::commit();
        }catch (Exception $e){
            $this::rollback();
            $e->getMessage();
            return retu_json(400,'错误');
        }
        return true;
    }

    // 售后服务列表
    public function list($base)
    {
        $oredr = 'add_time desc';
        list($page,$limit) =  $base->getSetDefaultParams("page|1,limit|5");
        $get = ['page'=>$page,'limit'=>$limit];
        $where = [['is_delete','=',0],['uid','=',$base->user->id],['is_display','=',1]];
        $this->queryList($get,'id,order_id,order_orn,type,price,add_time,status',$where,$oredr);
        // 1-待审核，2-等待买家寄货，3-等待卖家收货，4-已完成，5-已拒绝
        foreach($this->modelList as $k => $item){
            // 此处先后端进行类型转换
            $this->list['data'][$k]['type'] = $this->list['data'][$k]['type'] == 2 ? 1 : 2;
            // 关联到售后服务表的数据  拿取到数量
            if($item->oneServiceGoods){
                $this->list['data'][$k]['num'] = $item->oneServiceGoods->num;
            }
            // 关联到订单详情表 拿取商品数据
            if($item->oneOrderInfo){
                $this->list['data'][$k]['img'] = $item->oneOrderInfo['json']['good_attr']['img'];
                $this->list['data'][$k]['title'] = $item->oneOrderInfo['json']['goods']['title'];
                $this->list['data'][$k]['name'] = $item->oneOrderInfo['json']['goods']['name'];
            }
        }
    }

    // 售后服务详情
    public function getOne($base)
    {
        list($id) =  $base->getSetDefaultParams("id|-1");
        $one = $this::where('uid',$base->user->id)->find($id);
        if(!$one)return retu_json(400,'记录为空');
        // 关联到售后服务表的数据  拿取到数量
        if($one->oneServiceGoods)
            $one['num'] = $one->oneServiceGoods->num;
        // 关联到订单详情表 拿取商品数据
        if($one->oneOrderInfo){
            $one['img'] = $one->oneOrderInfo['json']['good_attr']['img'];
            $one['title'] = $one->oneOrderInfo['json']['goods']['title'];
            $one['name'] = $one->oneOrderInfo['json']['goods']['name'];
            $one['goods_price'] = $one->oneOrderInfo['json']['good_attr']['price'];
        }
        // 如果状态为  2 已审核  下一步是待买家发货 需要 显示卖家收货人
        if($one->status == 2){
            $ReceiptModel = Receipt::where('shop_id',$one['shop_id'])->field('name,tel,address')->find();
            if($ReceiptModel)
                $one['address'] =  $ReceiptModel->toArray();
        }
//        $LogisticsList =  (new Logistics())->getListCache();

        //物流 -- 模型数据
        $LogisticsModel = new Logistics();
        $LogisticsList =  $LogisticsModel->getLogistics();
        // 如果 有买家发送给商家的物流信息id
        // 买家物流信息
        $changeExpress_show = false;
        $changeExpress = [];
        if($one->change_express_id > 0 && $one->oneChangeExpress){
            $changeExpress = [
                'express_sn' => $one->oneChangeExpress->express_sn,
                'company' => $LogisticsModel->getNames($LogisticsList,$one->oneChangeExpress->company),
                'desc' => $one->oneChangeExpress->desc
            ];
            $changeExpress_show = true;
        }
            
        // 如果 有商家发送给买家的物流信息id
        $merchantExpress_show = false;
        $merchantExpress = [];
        if($one->merchant_express_id > 0 && $one->oneMerchantExpress){
            $merchantExpress_show = true;
            $merchantExpress = [
                'desc' => $one->oneMerchantExpress->desc,
                'express_sn' => $one->oneMerchantExpress->express_sn,
                'company' => $LogisticsModel->getNames($LogisticsList,$one->oneMerchantExpress->company),
            ];
        }
            
//        unset($one['oneOrderInfo']);
//        unset($one['oneServiceGoods']);
//        return $one;

        // 文字状态更改



        return [
            'id' => $one->id,
            'service_sn' => $one->service_sn, // 服务号
            'type' =>$one['type']  == 2 ? 1 : 2, // 类型 此处先后端进行转换类型
            "price"=> $one->price, // 申请退款金额
            "refund" => $one->refund, // 实际退款金额
            "status" => $one->status, // 状态
            "apply_reason" => $one->apply_reason, // 申请理由
            "reply_reason" => $one->reply_reason, // 回复理由
            "add_time" => $one->add_time, // 添加时间
            "num"=> $one->num, // 数量
            "img"=> $one->img, // 图片
            "title"=> $one->title, // 标题
            "name"=> $one->name, // 名称
            "goods_price"=> $one->goods_price, // 商品价格
            "changeExpress" => $changeExpress, // 买家物流信息
            "changeExpress_show" => $changeExpress_show, // 是否显示买家物流信息
            "merchantExpress"=>$merchantExpress, //商家发货 物流信息
            "merchantExpress_show" => $merchantExpress_show, //是否显示商家物流信息
            "address" => $one['address']
        ];
    }

    // 售后服务  -  退货更新订单关联
    public function returnExpress($base)
    {
        list($id,$company_id,$express_sn) =  $base->getSetDefaultParams("id|-1,company_id|-1,express_sn|-1");
        $one = $this::where('uid',$base->user->id)->find($id);
        $model = new Logistics();
        $logisticsList =  $model->getAllList();
        $logisticsBool = true;
        foreach($logisticsList as $item){
            if($item['id'] == $company_id){
                $logisticsBool = false;
                break;
            }
        }
        // 物流公司不存在
        if($logisticsBool)
            return retu_json(400, '物流信息不存在');
        if(!$one)
            return retu_json(400,'记录为空');
        // 状态不等于  商品已审核 等待买家寄货
        if($one->status != 2)
            return retu_json(400,'状态下一步等待买家寄货');
        $this::startTrans();
        try{
            // 物流信息表插入
            $id = Express::insertGetId([
                'type' => 2, // 类型2 为售后
                'relation_id' => $one->id,
                'company' => $company_id, // 物流公司
                'express_sn' => $express_sn, // 运单号
                'add_time' => time()
            ]);
            if(!$id)
                return retu_json(400,'信息错误');
            $s = $this::where('id',$one->id)->update([
                'status' => 3, // 改变状态
                'change_express_id' => $id // 买家发货给商家 换货或者退货都需要
            ]);
            if(!$s)
                return retu_json(400,'状态错误，重新尝试');
            ServiceGoods::where('service_id',$one->id)->update([
                'status' => 1, // 寄货中
            ]);
            $this::commit();
            return retu_json(200,'操作ok');
        }catch (Exception $e){
            $this::rollback();
            return retu_json(400,'操作失败');
        }
    }

    /**
     * 店铺售后列表
     */
    public function shopList($user, $param){
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopOne = $shopList['data'];
        // 参数拿取
        $oredr = 'add_time desc';
        $page = isset($param['page']) ?  $param['page'] : 1;
        $limit = isset($param['limit']) ?  $param['limit'] : 1;
        $get = ['page'=>$page,'limit'=>$limit];
        $where = [['is_delete','=',0],['shop_id','=',$shopOne->id],['is_display','=',1]];
        $this->queryList($get,'id,order_goods_id,type,price as apply_price,add_time,status',$where,$oredr);
        $status = [
            '审核中',
            '审核通过',
            '待买家发货',
            '商家待收货',
            '商家处理中',
            '完结',
            '拒绝'
        ];
        // 1-待审核，2-等待买家寄货，3-等待卖家收货，4-已完成，5-已拒绝
        foreach($this->modelList as $k => &$item){
            // 状态描述
            $this->list['data'][$k]['status'] = $status[$this->list['data'][$k]['status']];
            // 关联到售后服务表的数据  拿取到数量
            if($item['order_goods_id'] && $item->oneOrderGoods){
                $itemArrs = $item->oneOrderGoods->toArray();
                $this->list['data'][$k]['num'] = $itemArrs['num'];
                $this->list['data'][$k]['img'] = $itemArrs['img'];
                $this->list['data'][$k]['img'] = $itemArrs['img'];
                $this->list['data'][$k]['price'] = $itemArrs['price'];
                $this->list['data'][$k]['title'] = $itemArrs['title'];
                $this->list['data'][$k]['attr_str'] = $itemArrs['attr_str'];
                $this->list['data'][$k]['total'] = $itemArrs['total'];
                // unset($item['oneOrderGoods']);
            }
            unset($item['order_goods_id']);
        }
        return $this->list;
    }

    // 售后详情 - 店铺 - 商家管理操作
    public function getShopOne($user, $param){
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopOne = $shopList['data'];

        $id = isset($param['id']) ? $param['id'] : $param['id'];
        $one = $this::where('uid',$user->id)->find($id);
        if(!$one)return retu_json(400,'记录为空');

        // 照片
        $coverImgs = [];
        if($one->cover)$coverImgs = explode(',',$one->cover);

        // 显示卖家收货人
        $address = [
            'name' => 'xxx',
            'tel' => 'xxxxxxxxx',
            'address' => '请在后台填写收货地址'
        ];
        $address_show = false;
        if($ReceiptModel = Receipt::where('shop_id',$shopOne->id)->field('name,tel,address')->find()){
            $address =  $ReceiptModel->toArray();
            $address_show = true;
        }
        
        // 显示买家信息
        $nickname = '风再起时';
        if($user = User::where('id',$one->uid)->field('nickname')->find())$nickname = $user['nickname'];

        $bc = new Bc();

        // 订单号
        $order_orn = $one->order_id;
        $pay_time = '';
        if($order = Order::where('id',$order_orn)->field('order_sn,pay_time')->find()){
            $order_orn = $order['order_sn'];
            $pay_time = $order['pay_time'];
        }

        // 商品总额, 运费
        $sum_price = 0;$freight  = 0;
        $total = 0;
        if($one->order_goods_id > 0 && $orderGoods = OrderGoods::where('id',$one->order_goods_id)->field('price,freight,num,total')->find()){
            // 总额 // 运费
            $sum_price =  $bc->calcMul($orderGoods['price'],$orderGoods['num'],2);
            $freight = $orderGoods['freight'] / 100;
            $total = $orderGoods['total'];
        }

        //物流 -- 模型数据
        $LogisticsModel = new Logistics();
        $LogisticsList =  $LogisticsModel->getLogistics();

        // 买家物流信息
        $changeExpress_show = false;
        $changeExpress = [];
        if($one->change_express_id > 0 && $one->oneChangeExpress){
            $changeExpress_show = true;
            $changeExpress = [
                'company' => $LogisticsModel->getNames($LogisticsList,$one->oneChangeExpress->company),
                'express_sn' => $one->oneChangeExpress->express_sn,
                'desc' => $one->oneChangeExpress->desc
            ];
        }

        // 如果 有商家发送给买家的物流信息id
        $merchantExpress_show = false;
        $merchantExpress = [];
        if($one->merchant_express_id > 0 && $one->oneMerchantExpress){
            $merchantExpress_show = true;
            $merchantExpress = [
                'company' => $LogisticsModel->getNames($LogisticsList,$one->oneMerchantExpress->company),
                'express_sn' => $one->oneMerchantExpress->express_sn,
                'desc' => $one->oneMerchantExpress->desc,
            ];
        }

        // 订单商品
        $orderGoodsOne = OrderGoods::where('id',$one['order_goods_id'])->field('img,title,num')->find();

        // 文字状态更改
        $status = [
            '待审核',
            '审核通过',
            '待买家发货',
            '商家待收货',
            '商家处理中',
            '完结',
            '拒绝'
        ];

        return [
            'id' => $one->id,
            'type' =>$one['type'], // 类型
            "nickname" => $nickname, // 用户昵称
            'order_orn' => $order_orn, // 订单号
            "pay_time" => $pay_time, // 订单支付时间
            "coverImgs" => $coverImgs, // 照片信息
            "price"=> $one->price, // 申请退款金额
            "refund" => $one->refund, // 实际退款金额
            "status" => $one->status, // 状态
            "status_str" => $status[$one->status], // 状态文字
            "apply_reason" => $one->apply_reason, // 申请理由
            "reply_reason" => $one->reply_reason, // 回复理由
            "add_time" => $one->add_time, // 添加时间
            "sum_price"=> $sum_price, // 商品价格
            "freight" =>$freight, // 运费
            "total" => $total, // 实际支付
            "address" => $address, // 商家收货人 信息 
            "address_show" => $address_show, // 是否显示 商家收货人
            "changeExpress" => $changeExpress, // 买家物流信息
            "changeExpress_show" => $changeExpress_show, // 是否显示买家物流信息
            "merchantExpress"=>$merchantExpress, //商家发货 物流信息
            "merchantExpress_show" => $merchantExpress_show, //是否显示商家物流信息
            "img" => $orderGoodsOne->img,
            "title" => $orderGoodsOne->title,
            "num" => $one->apply_num
        ];
    }

    /**
     * 同意审核
     */
    public function toYesReview($user,$param){
        return retu_json(400,'麻烦到后台处理');
        $id = isset($param['id']) ? $param['id'] : 0;
        if(!$id || $id <= 0) return retu_json(400,'序号必须传入');
        if(!$one = $this::find($id))return retu_json(400,'没有该记录');
        if($one->staut != 0)return retu_json(400,'此订单不是待审核');
        // 拿取店铺信息
        $shopModel = new ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopOne = $shopList['data'];
    }

    /**
     * 拒绝审核
     */
    public function toNoReview($user,$param){
        return retu_json(400,'麻烦到后台处理');
        $id = isset($param['id']) ? $param['id'] : 0;
        $desc = isset($param['desc']) ? $param['desc'] : 0;
        if(!$id || $id <= 0) return retu_json(400,'序号必须传入');
        if(!$desc || strlen($desc) <= 2) return retu_json(400,'拒绝理由不得为空');
        if(!$one = $this::find($id))return retu_json(400,'没有该记录');
        if($one->staut != 0)return retu_json(400,'此订单不是待审核');
        return retu_json(400,'麻烦到后台处理');
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopOne = $shopList['data'];
    }

    /**
     * 一对一关联
     */
    public function oneServiceGoods()
    {
        return $this::hasOne(ServiceGoods::class,'service_id','id');
    }

    /**
     * 一对一  关联到订单商品表
     */
    public function oneOrderGoods()
    {
        return $this::hasOne(OrderGoods::class,'id','order_goods_id');
    }


    /**
     * 关联订单详情表
     */
    public function oneOrderInfo()
    {
        return $this::hasOne(OrderInfo::class,'oid','order_id');
    }

    /**
     * 关联物流信息表 -  买家发给商家的物流信息
     */
    public function oneChangeExpress()
    {
        return $this::hasOne(Express::class,'id','change_express_id');
    }

    /**
     * 关联物流信息表 -  商家发给买家的物流信息
     */
    public function oneMerchantExpress()
    {
        return $this::hasOne(Express::class,'id','merchant_express_id');
    }
}
